<template>
    <div class="container">
        <el-dialog title="导入（注：仅显示已发布专场）" :visible.sync="dialogShow" width="1000px" :destroy-on-close="true"
                   :before-close="close">
            <!-- 第一行——操作按钮 -->
            <div class="filter-container">
                专题名称：
                <el-input v-model="title" class="mr20" placeholder="请输入" style="width: 300px" clearable/>

                <el-button class="el-icon-search" type="primary" style="width: 80px" @click="handleFilter">查询
                </el-button>
            </div>
            <!-- / 第一行——操作按钮 -->

            <!-- table表格 -->
            <el-table ref="multipleTable" :data="list" :stripe="true" style="width: 100%">
                <!--      <el-table-column type="selection" width="160px" > </el-table-column>  @selection-change="handleSelectionChange"-->
                <el-table-column align="center" label="专场头图" width="150px">
                    <template slot-scope="{ row }">
                        <el-image style="display: block;height: 50px" fit="cover" :src="row.imageFileId_dictText"/>
                    </template>
                </el-table-column>
                <!-- 标题 -->
                <el-table-column align="center" prop="title" label="专场名称" width="270px"/>


                <el-table-column align="center" prop="publishStatus_dictText" width="70px" label="状态">已发布
                </el-table-column>

                <el-table-column align="center" prop="publishTime" label="活动时间" width="250px">
                    <template slot-scope="{ row }">
                        <div class="date">
                            {{ $moment(row.startTime, 'yyyy-MM-DD HH:mm:ss').format('yyyy年MM月DD日') }} -
                            {{ $moment(row.endTime, 'yyyy-MM-DD HH:mm:ss').format('yyyy年MM月DD日') }}
                        </div>
                    </template>
                </el-table-column>

                <!-- 操作 -->
                <el-table-column label="操作" width="200px" fixed="right" align="center">
                    <template slot-scope="{ row, $index }">
                        <el-button v-if="1 != row.addStatus" type="text" @click="addItem(row, $index)">加入</el-button>
                        <el-button v-else type="text" @click="delItem(row, $index)">取消加入</el-button>

                        <!-- <el-button type="text" @click="topItem(row)">置顶</el-button> -->
                    </template>
                </el-table-column>
                <!-- / 操作 -->
            </el-table>
            <!-- / table表格 -->

            <!--      <pagination-->
            <!--        v-show="total > 0"-->
            <!--        :total="total"-->
            <!--        prev-text="上一页"-->
            <!--        next-text="下一页"-->
            <!--        layout="prev, pager, next, jumper"-->
            <!--        :page.sync="listQuery.page"-->
            <!--        :limit.sync="listQuery.limit"-->
            <!--        pageBackground="none"-->
            <!--      />-->

            <!-- 分页 -->
            <pagination
                v-show="total > 0"
                :total="total"
                next-text="下一页"
                layout="prev, pager, next, jumper"
                :page.sync="listQuery.pageNo"
                :limit.sync="listQuery.pageSize"
                @current-change="currentChange"
                @pagination="getList"
            />
            <!-- / 分页 -->
            <!--      <editDrawer ref="editDrawer" @refresh="refresh"/>-->

            <!--      <span slot="footer" class="dialog-footer">-->
            <!--        <el-button @click="dialogShow = false">取 消</el-button>-->
            <!--        <el-button type="primary" @click="submit"-->
            <!--          >确 定</el-button-->
            <!--        >-->
            <!--      </span>-->
        </el-dialog>
    </div>
</template>

<script>
import Pagination from '@/components/Pagination' // 分页
import {cmsContent_add, cmsContent_list} from '@/api/article'
import {blockDataAdd, blockData_list, createBlockDataId, blockDataDel} from '@/api/block'
import {listSpecialSession} from '@/api/special-session'

export default {
    components: {Pagination},
    props: {},
    data() {
        return {
            channelId: '',
            blockId: '',
            title: '', // 标题搜索（之所以单独列出，没有使用listQuery，是因为接口需要传递**标题**，以表示模糊搜索，从而会造成回显问题）
            // 时间选择器
            list: [], // 内容列表
            total: 0, // 总页数
            listLoading: true,

            // 查询参数
            listQuery: {
                channelId: null,
                title: null,
                publishStatus: 1,
                pageNo: 1,
                pageSize: 10,
                pubFlag: true
            },
            dialogShow: false,
            multipleSelection: [] // 选择的内容
            // query: {},
            // total: 1,
        }
    },
    // 生命周期 - 创建完成（可以访问当前this实例）
    created() {
    },
    // 生命周期 - 挂载完成（可以访问DOM元素）
    mounted() {
    },
    // 销毁
    destroyed() {
    },
    // 方法
    methods: {
        cancelForm() {
            this.loading = false
            this.dialog = false
            // clearTimeout(this.timer);
        },
        // 分页数据
        getList() {
            console.log('-----获得分页数据-------')
            this.listLoading = true
            listSpecialSession(this.listQuery).then(response => {
                const list = response.result.records

                for (let i = 0; i < list.length; i++) {
                    list[i].addStatus = 0
                    // let  element=list[i];
                    // console.log(element);
                }
                this.list = list

                this.total = response.result.total
                this.listLoading = false

                this.get_blockData_list(this.list)

                // this.$refs.multipleTable.toggleRowSelection(this.list[1]);
                // setTimeout(function () {
                //   this.$refs.multipleTable.toggleRowSelection(this.list[1]);
                // },1000)
            })
        },
        get_blockData_list(list) {
            // 如果已经加入 则设置为选中效果
            console.log('-----===================>获得选中的数据数据-------')
            this.listLoading = true
            const blockDataQuery = {}
            blockDataQuery.blockId = this.blockId
            let sourceId = ''
            for (let i = 0; i < list.length; i++) {
                sourceId += list[i].id
                if (i + 1 != list.length) sourceId += ','
            }
            blockDataQuery.sourceId = sourceId

            blockData_list(blockDataQuery).then(response => {
                const data_list = response.result.records
                for (let i = 0; i < list.length; i++) {
                    for (let d = 0; d < data_list.length; d++) {
                        console.log('========data_list====》 ' + data_list[d].sourceId)
                        if (list[i].id == data_list[d].sourceId) {
                            console.log('============》相同' + list[i].id)
                            // this.$refs.multipleTable.toggleRowSelection(list[i]);
                            list[i].addStatus = 1
                        }
                    }
                } // end of outter for

                // setTimeout(function () {
                //   this.$refs.multipleTable.toggleRowSelection(this.list[1]);
                // },1000)
            })
        },
        close() {
            this.title = ''
            this.dialogShow = false
            this.list = []
            this.total = 0
        },
        // 搜索
        handleFilter() {
            this.listQuery.page = 1

            console.log('search:' + this.title)
            if (this.title != '' && this.title != null) {
                this.listQuery.title = this.title
            } else {
                this.listQuery.title = ''
            }

            this.getList(this.listQuery)
        },
        currentChange(e) {
            console.log('currentChange' + e)
        },

        handleSelectionChange(val) {
            console.log('handleSelectionChange' + val)
            this.multipleSelection = val
        },
        //
        // // 保存——radio方式
        // submit() {
        //   console.log("submit")
        //   console.log("submit"+this.multipleSelection)
        //
        //   if(null==this.multipleSelection||0==this.multipleSelection.length){
        //     this.$message({
        //       message: '亲，你还没选择任何记录！',
        //       type: 'warning'
        //     });
        //     return;
        //   }
        //
        //   let blocks=[];
        //   let that=this;
        //   let i=0;
        //   this.multipleSelection.forEach(function(row) {
        //     console.log("您选择的数据："+row.id +" " +row.title);
        //     let b={};
        //     b.id=that.blockId+"-"+row.id;
        //     b.sourceId=row.id;
        //     b.open=true;
        //     b.type="cms_content";
        //     b.title=row.title;
        //     b.blockId=that.blockId;
        //     b.image=row.thumb;
        //     b.sequence=++i;
        //
        //     blocks.push(b);
        //   });
        // },//end of function

        // 删除
        delItem(row, index) {
            const id = this.$createBlockDataId(this.blockId, row.id)
            blockDataDel({id: id}).then(response => {
                row.addStatus = 0
                this.$message({
                    type: 'success',
                    message: '删除成功!'
                })

                this.$emit('refresh')
            })

            // this.$confirm('确定要移除吗, 是否继续?', '提示', {
            //   confirmButtonText: '确定',
            //   cancelButtonText: '取消',
            //   type: 'warning'
            // }).then(() => {
            //   blockDataDel({ id: e.id }).then(response => {
            //     this.$message({
            //       type: 'success',
            //       message: '删除成功!'
            //     })
            //     this.refresh()
            //   })
            //   // this.list.splice(index, 1)
            // }).catch(() => {
            //   this.$message({
            //     type: 'info',
            //     message: '已取消删除'
            //   })
            // })
        },
        // 保存
        addItem(row) {
            // console.log("submit2")

            const blocks = []
            const that = this
            let i = 0

            // console.log("您选择的数据："+row.id +" " +row.title,index);
            const b = {}
            b.id = this.$createBlockDataId(that.blockId, row.id)
            b.sourceId = row.id
            b.open = true
            b.type = 'special'
            b.title = row.title
            b.blockId = that.blockId
            b.image = row.imageFileId
            b.sequence = ++i

            blocks.push(b)

            row.addStatus = 1
            // this.list[index].status=1;

            blockDataAdd(blocks).then(response => {
                if (response.code == '200') {
                    this.$message({
                        type: 'success',
                        message: '添加成功!'
                    })
                } else {
                    this.$message({
                        type: 'error',
                        message: '添加失败!'
                    })
                }

                // this.drawerShow = false
                this.$emit('refresh')
            })
        }, // end of function
        show(blockId) {
            this.blockId = blockId

            console.log('打开窗口:', blockId)
            this.getList()
            this.dialogShow = true
        }
    }
}
</script>
<style lang="scss" scoped></style>
